package cn.hncj.lyc.controller.pay;

import com.alibaba.fastjson.JSON;
import com.github.wxpay.sdk.WXPayUtil;

import cn.hncj.lyc.bean.OrderManagement;
import cn.hncj.lyc.service.OrderStateService;
import cn.hncj.lyc.utils.wxpay.HttpClient;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 拓薪教育 -- 腾讯课堂认证机构
 * 樱木老师
 *
 * 查询订单是否支付成功
 */
@Controller
@RequestMapping("/")
//@WebServlet(name = "queryPayStatusServlet",urlPatterns = "/queryPayStatusServlet")
public class QueryPayStatusServlet extends HttpServlet {		
	/**
	 * 
	 */
    @RequestMapping("/queryPayStatusServlet")
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 设置响应编码
            resp.setContentType("application/json;charset=UTF-8");
            // 获取到订单编号
            String out_trade_no = req.getParameter("out_trade_no");
            // 定义map集合
            Map<String,Object > resultMap = new HashMap<>();
            // 定义次数
            int times = 0;
            // 写一个循环的查询
            while(times <= 10){
                // 每循环一次，去调用一次查询的接口
                times++;
                // 加睡眠的操作
                Thread.sleep(5000);
                // 调用查询接口方法
                Map<String, String> map = getPayStatus(out_trade_no);
                // 根据map返回值，判断支付是否成功
                if("SUCCESS".equals(map.get("result_code")) && "SUCCESS".equals(map.get("trade_state"))){
                    resultMap.put("success",true);
                    String result = JSON.toJSONString(resultMap);
                    resp.getWriter().print(result);
                    //orderStateService.updateOrderState(om);
                    //System.out.println(om);
        			//model.addAttribute("orderpayid", "成功");
        			System.out.println("0000000000000000000000000");
                    return;
                }
            }

            // 支付超时
            resultMap.put("success",false);
            resultMap.put("message","支付超时");
            String result = JSON.toJSONString(resultMap);
            resp.getWriter().print(result);
            return;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送请求，查询支付状态
     *
     * @param out_trade_no
     * @return
     */
    public Map<String, String> getPayStatus(String out_trade_no) {
        // 查询支付状态的请求地址
        HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
        // 调用微信的查询订单支付状态API
        Map<String, String> paramMap = new HashMap<String, String>();
        // 公众账号ID
        paramMap.put("appid", "wx0609f8351dca9750");
        // 商户号
        paramMap.put("mch_id", "1536725911");
        // 商户的订单号
        paramMap.put("out_trade_no", out_trade_no);
        // 随机字符串
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());

        try {
            // 把paramMap转成xml  转xml时带有签名
            String paramXml = WXPayUtil.generateSignedXml(paramMap, "txjavayingmulaoshi01234567891234");
            // 设置参数
            httpClient.setXmlParam(paramXml);
            // 发送post请求
            httpClient.post();
            // 获取返回结果
            String content = httpClient.getContent();
            // 根据返回结果生成map集合
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);

            return resultMap;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
